package com.orange.lockscreen.layers.finger;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.orange.lockscreen.R;
import com.orange.lockscreen.SlatHashMap;
import com.orange.lockscreen.layers.SlatPanel;

/**
 * 
 * TapPanel: show single cirle animation orignating from point where screen
 * touched.
 * 
 */
public class TapPanel extends SlatPanel {

	private static final int	FIRST_DISAPPEAR	= 1;
	private static final int	TIME_DISAPPEAR	= 600;

	private ImageView			mFirstCircle;
	private ImageView			mSecondCircle;
	private CircleSlat			mTapSlat;

	private H					mH;
	private Animation			mAlphaAnimation1;
	private Animation			mAlphaAnimation2;

	private int					mTapRow;

	class H extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FIRST_DISAPPEAR:
				break;
			default:
				break;
			}
		}
	}

	public TapPanel(Context context) {
		super(context);
	}

	@Override
	protected void init() {
		mH = new H();

		mTapSlat = new CircleSlat(getContext());
		mTapSlat.setClipChildren(true);
		addView(mTapSlat);

		mFirstCircle = mTapSlat.getFirstCircleView();
		mSecondCircle = mTapSlat.getSecondCircleView();

		mAlphaAnimation1 = AnimationUtils.loadAnimation(getContext(),
				R.anim.tap_anim);
		mAlphaAnimation2 = AnimationUtils.loadAnimation(getContext(),
				R.anim.tap_anim);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int top = SlatHashMap.getSlatTop(mTapRow);
		int rowHeight = SlatHashMap.getSlatHeight(mTapRow);
		mTapSlat.layout(0, top, r - l, top + rowHeight);
	}

	public void showOnSingleTap(int x, int y, int row) {
		keepDate(x, y, row);
		showFirstCircleAnim();
		mH.sendEmptyMessageDelayed(FIRST_DISAPPEAR, TIME_DISAPPEAR);
	}

	public void showOnDoubleTap() {
		mSecondCircle.setVisibility(VISIBLE);
		mSecondCircle.startAnimation(mAlphaAnimation2);
		mH.sendEmptyMessageDelayed(FIRST_DISAPPEAR, TIME_DISAPPEAR);
	}

	private void keepDate(int x, int y, int row) {
		int top = SlatHashMap.getSlatTop(row);
		mTapSlat.setCirclePosition(x, y - top);
		mTapRow = row;
	}

	private void showFirstCircleAnim() {
		boolean isAnimating = mH.hasMessages(FIRST_DISAPPEAR);
		if (isAnimating) {
			mFirstCircle.clearAnimation();
			mH.removeMessages(FIRST_DISAPPEAR);
		}
		mFirstCircle.setVisibility(VISIBLE);
		mTapSlat.requestLayout();
		mFirstCircle.startAnimation(mAlphaAnimation1);
	}
}
